import 'dart:convert';

import 'package:ecy_app_flutter/ecycommon/EcyCommonWidgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../EcyRouter.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../../goods/widgets/common/Debouncer.dart';
import '../../my/model/EcyMyOrder.dart';
import '../../my/model/EcyMyOrderCommodity.dart';
import '../../my/model/EcyMyOrderListModel.dart';


class EcyMyBuyListSearchPage extends EcyCommonBaseWidget {
  EcyMyBuyListSearchPage({required super.key});

  @override
  _EcyMyBuyListSearchPageState createState() {
    return _EcyMyBuyListSearchPageState(this);
  }
}

class _EcyMyBuyListSearchPageState extends EcyCommonBaseWidgetState with SingleTickerProviderStateMixin {
  late EcyCommonBaseWidget controller;
  _EcyMyBuyListSearchPageState(EcyCommonBaseWidget vc) {
    controller = vc;
  }
  late EcyMyOrderListModel ecyMyOrderListModel =
  EcyMyOrderListModel(0, 0, 0, []);
  final List<String> tabs = ['全部', '待寄存', '待取货', '已完成'];
  late TabController _tabController;
  final List<ScrollController> _tabScrollControllers = [];
  int _currentPage = 1;
  bool _hasMore = true;
  bool showToTopBtn = false;
  bool isLoading = false;

  final TextEditingController _searchController = TextEditingController();
  String searchKey = "";
  final Debounce debounce = Debounce();

  @override
  void initState() {
    super.initState();

    _tabController = TabController(length: tabs.length, vsync: this);
    _tabController.addListener(() {
      if (_tabController.animation!.value == _tabController.index) {
        _handleTabSelection(_tabController.index); //获取点击或滑动页面的索引值
      }
    });

    // 初始化每个 Tab 页的控制器
    for (int i = 0; i < tabs.length; i++) {
      ScrollController scrollController = ScrollController();
      _tabScrollControllers.add(scrollController);
      scrollController.addListener(() {
        print(scrollController.position.pixels);
        print('-------------');
        print(scrollController.position.maxScrollExtent);
        if (scrollController.position.pixels >=
            scrollController.position.maxScrollExtent) {
          if(!isLoading) {
            _onLoadMore();
          }
        }

        print(scrollController.offset); //打印滚动位置
        if (scrollController.offset < 300 && showToTopBtn) {
          setState(() {
            showToTopBtn = false;
          });
        } else if (scrollController.offset >= 300 && showToTopBtn == false) {
          setState(() {
            showToTopBtn = true;
          });
        }
      });
    }
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    _tabController.dispose();
    // 释放所有控制器
    for (var controller in _tabScrollControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  Future<void> requestData({int pageIndex = 1, int type = 0}) async {
    controller.showLoading();
    await requestMyOrderListData(pageIndex, type);
    controller.dismissLoading();
  }

  _handleTabSelection(index) {
    requestData(type: index);
  }

  Future<void> _onRefresh() async {
    setState(() {
      _currentPage = 1;
    });
    requestData(pageIndex: _currentPage, type: _tabController.index);
  }

  Future<void> _onLoadMore() async {
    if (isLoading || _hasMore) {
      return;
    }
    setState(() {
      isLoading = true;
    });
    _currentPage++;
    await requestData(pageIndex: _currentPage, type: _tabController.index);
    setState(() {
      isLoading = false;
    });
  }

  //查询我的订单列表
  Future<void> requestMyOrderListData(pageIndex, type) async {
    super.requestData();
    Map<String, dynamic> body = {
      "pageSize": 10,
      "pageIndex": pageIndex,
      "type": type
    };
    var response = await EcyRequestbasemanager().get("/app/api/app/user/order", body);

    if (response != null) {
      var _myOrderRespModel =
      EcyApiCommonResponse.fromJson(response, (response) => json);
      if (_myOrderRespModel.code == 0 || _myOrderRespModel.code == 200) {
        EcyMyOrderListModel _ecyMyOrderListModel =
        EcyMyOrderListModel.fromJson(response["data"]);
        setState(() {
          _hasMore = _ecyMyOrderListModel.total > _currentPage;
          if (pageIndex == 1) {
            ecyMyOrderListModel.records.clear();
          }
          _currentPage = _ecyMyOrderListModel.pages;
          ecyMyOrderListModel.records.addAll(_ecyMyOrderListModel.records);
        });
      }
    }
  }

  void searchData() async {

  }


  @override
  Widget build(BuildContext context) {
    Widget avatar = Image.asset('assets/images/ic_head.jpeg', width: 24);
    Widget image = Image.asset('assets/images/ic_head.jpg', width: 80);

    return DefaultTabController(
        length: tabs.length,
        child: Scaffold(
          backgroundColor: Color(0xFFF5F5F5),
          appBar: AppBar(
              automaticallyImplyLeading: false,
              titleSpacing: 0,
              title: Wrap(
                alignment: WrapAlignment.spaceBetween,
                direction: Axis.horizontal,
                spacing: 10.w,
                crossAxisAlignment: WrapCrossAlignment.center,
                children: [
                  Container(
                      height: 36.w,
                      margin: EdgeInsets.only(left: 10.w),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(8.r)),
                        color: const Color(0x0A000000), //设置背景色为黑色
                      ),
                      width: MediaQuery.of(context).size.width - 60.w,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Padding(padding: EdgeInsets.only(left: 5.w)),
                          Image(
                              image: const AssetImage(
                                  'assets/images/ic_home_search.png'),
                              width: 24.w,
                              height: 24.w),
                          // 左侧图标按钮
                          Expanded(
                            // 使TextField扩展剩余空间
                            child: Container(
                                alignment:Alignment.center ,
                                // margin: EdgeInsets.only(left: 4.w, bottom: 4.h),
                                height: 36.w,
                                child: TextField(
                                  controller: _searchController,
                                  autofocus: true,
                                  textAlignVertical: TextAlignVertical.center,
                                  decoration: InputDecoration(
                                    isCollapsed: true,
                                    hintText: "搜索",
                                    hintStyle: TextStyle(
                                        fontSize: 16.sp,
                                        fontWeight: FontWeight.w300,
                                        color: const Color(0x73000000)),
                                    border: InputBorder.none, // 移除默认边框，因为我们使用了Row布局
                                  ),
                                  onChanged: (String value) {
                                    debounce.setDuration(
                                        const Duration(milliseconds: 300), () {
                                      searchKey = value;
                                      searchData();
                                    });
                                  },
                                )),
                          ),
                          IconButton(
                              icon: const Icon(
                                Icons.clear,
                                color: Color(0x73000000),
                              ),
                              onPressed: () {
                                setState(() {
                                  _searchController.text = "";
                                });
                              }), // 右侧图标按钮
                        ],
                      )),
                  GestureDetector(
                      onTap: () {
                        EcyRouter.pop(context, "");
                      },
                      child: Text("取消",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              fontWeight: FontWeight.w400,
                              fontSize: 16.sp,
                              color: const Color(0xD9000000)))),
                ],
              ),
              centerTitle: true,
              backgroundColor: Colors.white,
              bottom: PreferredSize(
                preferredSize: const Size.fromHeight(40),
                child: Material(
                  color: const Color(0xFFF5F5F5),
                  child: TabBar(
                    controller: _tabController,
                    labelColor: Colors.black,
                    labelStyle: TextStyle(fontSize: 18),
                    unselectedLabelColor: Color(0xFF696969),
                    unselectedLabelStyle: TextStyle(fontSize: 14),
                    tabs: tabs.map((e) => Tab(text: e)).toList(),
                    indicatorColor: Colors.transparent,
                    overlayColor:
                    const WidgetStatePropertyAll(Colors.transparent),
                    dividerHeight: 0,
                  ),
                ),
              )),
          body: TabBarView(
              controller: _tabController,
              children: _getPagesWidget(tabs, avatar, image)
          ),
          floatingActionButton: !showToTopBtn ? null : FloatingActionButton(
              child: Icon(Icons.arrow_upward),
              mini: true,
              backgroundColor: Colors.white,
              onPressed: () {
                //返回到顶部时执行动画
                _tabScrollControllers[_tabController.index].animateTo(
                  0.0,
                  duration: Duration(milliseconds: 200),
                  curve: Curves.ease,
                );
              }
          ),
        )
    );
  }

  List<Widget> _getPagesWidget(List<String> tabs, Widget avatar, Widget image) {
    return tabs.map((e) {
      final tabIndex = tabs.indexOf(e);
      if (_tabController.index != tabIndex ||
          ecyMyOrderListModel.records.isEmpty) {
        return RefreshIndicator(
          onRefresh: _onRefresh,
          child: ListView.builder(
            shrinkWrap: true,
            physics: const AlwaysScrollableScrollPhysics(),
            padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
            itemCount: 1,
            itemBuilder: (context, index) {
              return Column(children: [
                Image.asset('assets/images/empty/ic_empty_orders.png',
                    width: 150, height: 150),
                const Text('暂无订单',
                    style: TextStyle(fontSize: 18, color: Colors.grey)),
              ]);
            },
          ),
        );
      }
      return RefreshIndicator(
        onRefresh: _onRefresh,
        child: ListView.builder(
          controller: _tabScrollControllers[tabIndex],
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
          itemCount: ecyMyOrderListModel.records.length,
          itemBuilder: (context, index) {
            print(index);
            print(ecyMyOrderListModel.records.length);

            EcyMyOrder currOrder = ecyMyOrderListModel.records[index];
            return _buildOrderCard(currOrder, avatar, image);
          },
        ),
      );
    }).toList();
  }

  // 加载更多提示组件
  Widget _buildLoadMoreIndicator() {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 16),
      child: Center(
        child: _hasMore ? CircularProgressIndicator() : Text("没有更多数据了~"),
      ),
    );
  }

  Widget _buildOrderCard(EcyMyOrder myOrder, Widget avatar, Widget image) {
    List<EcyMyOrderCommodity> commodities = myOrder.commodities ?? [];
    if (commodities.isEmpty) {
      return const Text('有谷气');
    }
    EcyMyOrderCommodity order = commodities[0];
    if (commodities.length == 1) {
      return GestureDetector(
          child: Card(
            color: Colors.white,
            margin: const EdgeInsets.only(bottom: 10),
            child: Padding(
              padding: const EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            ClipOval(child: avatar),
                            const Padding(padding: EdgeInsets.only(left: 8)),
                            Text(order.shopName ?? '买家昵称',
                                style: const TextStyle(
                                    fontSize: 14, color: Colors.black)),
                          ]),
                      Text(order.status ?? '待寄存',
                          style: TextStyle(fontSize: 16, color: Colors.red)),
                    ],
                  ),
                  const Padding(padding: EdgeInsets.only(top: 12)),
                  Flex(
                    direction: Axis.horizontal,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: SizedBox(
                          height: 70,
                          width: 70,
                          child: ClipRRect(
                              borderRadius: BorderRadius.circular(5.0),
                              child: image),
                        ),
                      ),
                      const Padding(padding: EdgeInsets.only(right: 6)),
                      Expanded(
                        flex: 3,
                        child: SizedBox(
                          height: 80.0,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(order.name ?? '谷子',
                                  style: const TextStyle(
                                      fontSize: 16, color: Colors.black),
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis),
                              Text('保存时间：2025-02-24 12:00:48',
                                  style: TextStyle(
                                      fontSize: 13,
                                      color: const Color(0xFF8C8C8C)
                                          .withOpacity(0.8)),
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis),
                            ],
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: SizedBox(
                          height: 80.0,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              const Padding(
                                  padding: EdgeInsets.only(bottom: 2)),
                              Text('￥${order.price ?? 0.00}',
                                  style: const TextStyle(
                                      fontSize: 16, color: Colors.black),
                                  textAlign: TextAlign.right),
                              const Padding(
                                  padding: EdgeInsets.only(bottom: 2)),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                  const Padding(padding: EdgeInsets.only(top: 14)),
                  Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                    SizedBox(
                      height: 34.h,
                      width: 100.h,
                      child: TextButton(
                          onPressed: () {},
                          style: const ButtonStyle(
                            foregroundColor:
                            WidgetStatePropertyAll(Color(0xFF262626)),
                            side: WidgetStatePropertyAll(BorderSide(
                                color: Color(0xFFBFBFBF), width: 0.8)),
                          ),
                          child: const Text(
                            '删除',
                            style: TextStyle(
                              height: 1.0,
                              leadingDistribution:
                              TextLeadingDistribution.even, // 设置leading策略
                            ),
                          )),
                    ),
                    const Padding(padding: EdgeInsets.only(right: 8)),
                    SizedBox(
                      height: 32.h,
                      width: 100.h,
                      child: TextButton(
                          onPressed: () {},
                          style: const ButtonStyle(
                            alignment: Alignment.center,
                            foregroundColor:
                            WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                            side: WidgetStatePropertyAll(
                                BorderSide(color: Color(0xFFEA4B9B), width: 1)),
                          ),
                          child: const Text(
                            '编辑',
                            style: TextStyle(
                              height: 1,
                              leadingDistribution:
                              TextLeadingDistribution.even, // 设置leading策略
                            ),
                          )),
                    ),
                  ]),
                ],
              ),
            ),
          ),
          onTap: () {
            // 进入订单详情
            EcyRouter.push(context, EcyRouter.myConsignmentOrderDetailPage, myOrder.orderId);
          });
    } else {
      if (commodities.length > 3) {
        commodities = commodities.sublist(0, 4);
      }
      List<Widget> imageWidgets = commodities.map((e) {
        return SizedBox(
          height: 70,
          width: 70,
          child:
          ClipRRect(borderRadius: BorderRadius.circular(5.0), child: image),
        );
      }).toList();
      return GestureDetector(
          child: Card(
            color: Colors.white,
            margin: const EdgeInsets.only(bottom: 10),
            child: Padding(
              padding: const EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            ClipOval(child: avatar),
                            const Padding(padding: EdgeInsets.only(left: 8)),
                            Text(order.shopName ?? '买家昵称',
                                style: const TextStyle(
                                    fontSize: 14, color: Colors.black)),
                          ]),
                      Text(order.status ?? '待寄存',
                          style: TextStyle(fontSize: 16, color: Colors.red)),
                    ],
                  ),
                  const Padding(padding: EdgeInsets.only(top: 12)),
                  Flex(
                    direction: Axis.horizontal,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: SizedBox(
                          height: 70,
                          width: 70,
                          child: ClipRRect(
                              borderRadius: BorderRadius.circular(5.0),
                              child: image),
                        ),
                      ),
                      const Padding(padding: EdgeInsets.only(right: 6)),
                      Expanded(
                        flex: 3,
                        child: SizedBox(
                          height: 80.0,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(order.name ?? '谷子',
                                  style: const TextStyle(
                                      fontSize: 16, color: Colors.black),
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis),
                              Text('保存时间：2025-02-24 12:00:48',
                                  style: TextStyle(
                                      fontSize: 13,
                                      color: const Color(0xFF8C8C8C)
                                          .withOpacity(0.8)),
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis),
                            ],
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: SizedBox(
                          height: 80.0,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              const Padding(
                                  padding: EdgeInsets.only(bottom: 2)),
                              Text('￥${order.price ?? 0.00}',
                                  style: const TextStyle(
                                      fontSize: 16, color: Colors.black),
                                  textAlign: TextAlign.right),
                              const Padding(
                                  padding: EdgeInsets.only(bottom: 2)),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                  const Padding(padding: EdgeInsets.only(top: 14)),
                  Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                    SizedBox(
                      height: 34.h,
                      width: 100.h,
                      child: TextButton(
                          onPressed: () {},
                          style: const ButtonStyle(
                            foregroundColor:
                            WidgetStatePropertyAll(Color(0xFF262626)),
                            side: WidgetStatePropertyAll(BorderSide(
                                color: Color(0xFFBFBFBF), width: 0.8)),
                          ),
                          child: const Text(
                            '删除',
                            style: TextStyle(
                              height: 1.0,
                              leadingDistribution:
                              TextLeadingDistribution.even, // 设置leading策略
                            ),
                          )),
                    ),
                    const Padding(padding: EdgeInsets.only(right: 8)),
                    SizedBox(
                      height: 32.h,
                      width: 100.h,
                      child: TextButton(
                          onPressed: () {},
                          style: const ButtonStyle(
                            alignment: Alignment.center,
                            foregroundColor:
                            WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                            side: WidgetStatePropertyAll(
                                BorderSide(color: Color(0xFFEA4B9B), width: 1)),
                          ),
                          child: const Text(
                            '编辑',
                            style: TextStyle(
                              height: 1,
                              leadingDistribution:
                              TextLeadingDistribution.even, // 设置leading策略
                            ),
                          )),
                    ),
                  ]),
                ],
              ),
            ),
          ),
          onTap: () {
            // 进入订单详情
            EcyRouter.push(context, EcyRouter.myConsignmentOrderDetailPage, myOrder.orderId);
          });
    }
  }
}
